package ua.luxoft.parse;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

import ua.luxoft.fileinfo.FileInfo;

public class ParseFile {
	
	private HashMap<String, FileInfo> parseFile(File file){
		FileInfo fileInfo;
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(file, "r");
			if(raf.length() <= 0){
				throw new IllegalArgumentException("File is empty!");
			}
		} catch (FileNotFoundException e) {
			System.out.println("File " + file.getName() + " not found." );
		} catch (IOException e) {
			System.out.println("Some problem with file " + file.getName());
			e.printStackTrace();
		}
		HashMap<String, FileInfo> mapKeyFile = new HashMap<String, FileInfo>();
		String newLine;
		Scanner scan;
		String head = "";
		int firstLine = 0;
		fileInfo = new FileInfo();
		fileInfo.setFileName(file.getName());
		try {
			while((newLine = raf.readLine()) != null){
				scan = new Scanner(newLine);
				scan.useDelimiter("===");
				if(scan.hasNext()){
					if(firstLine != 0){
						fileInfo.setEndRead(raf.getFilePointer() - newLine.length() - 1);
					}
					head = scan.next();
					fileInfo.setHead(head);
					fileInfo.setStartRead(raf.getFilePointer() + 1);
					
				}
				if(raf.getFilePointer() == file.length()){
					fileInfo.setEndRead(raf.getFilePointer() - newLine.length() - 1);
				}
				mapKeyFile.put(head, fileInfo);
				firstLine++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		closeFile(raf);
		return mapKeyFile;
	}
	
	private void closeFile(RandomAccessFile raf){
		try {
			raf.close();
		} catch (IOException e) {
			System.out.println("Some problem in closing");
			e.printStackTrace();
		}
	}
	public HashMap<String, FileInfo> workWithFile(ArrayList<File> files){
		HashMap<String, FileInfo> map = new HashMap<String, FileInfo>();
		for(File file : files){
			map.putAll(parseFile(file));
		}
		return map;
	}
}
